<?php
/**
 * Logic.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/06/11
 * Time: 22:38
 */
namespace app\console\command\auto\tpl;

use app\api\util\Hump;
use think\Db;

class Logic
{
    static public function template($dir,$method,$table,$database)
    {
        if($method=='name') {
            $realTable = config('database.prefix').$table;
        }else{
            $realTable = $table;
        }
        $sql = "SELECT
			-- 列名称
			`column_name`,
			-- 列注释
			`column_comment`,
			-- 默认值
			`column_default`,
			-- 数据类型
			`data_type`,
			-- 字符最大长度
			`character_maximum_length`,
			-- 列键
			`column_key`,
			-- 能否为NULL
			`is_nullable`,
			-- 数值精度
			`numeric_precision`,
			-- 额外
			`extra`,
			-- 顺序位置
			`ordinal_position`,
			-- 列键
			`column_type`
		FROM
			`information_schema`.`columns`
		WHERE
			`table_schema` = '{$database}'
		AND `table_name` = '{$realTable}'
		AND `column_name` NOT IN ('id','create_ts','update_ts')";
        $columns = Db::query($sql);
        $validate1 = [];
        $validate2 = [];
        $saveData = [];
        $searchWhere = [];
        foreach($columns as $column){
            $validate1[] = "\t\t\t\"{$column['column_name']}\" => \"require\"";
            $validate2[] = "\t\t\t\"{$column['column_name']}.require\" => \"{$column['column_comment']}必填\"";
            // 字符类型：
            if(in_array($column['data_type'],['char','longtext','mediumtext','text','tinytext','varchar'])) {
                $saveData[] = "\t\t// {$column['column_comment']}\r\n\t\t\$this->saveData['{$column['column_name']}'] = (string)\$this->params['{$column['column_name']}'];";
            }
            // 日期和时间类型：
            else if(in_array($column['data_type'],['date','time','year','datetime','timestamp'])) {
                $saveData[] = "\t\t// {$column['column_comment']}\r\n\t\t\$this->saveData['{$column['column_name']}'] = \$this->params['{$column['column_name']}'];";
            }
            // 数值类型：
            else if(in_array($column['data_type'],['tinyint','smallint','mediumint','int','bigint'])) {
                $saveData[] = "\t\t// {$column['column_comment']}\r\n\t\t\$this->saveData['{$column['column_name']}'] = (int)\$this->params['{$column['column_name']}'];";
            }
            // 精度数值
            else if(in_array($column['data_type'],['float','double','decimal'])) {
                $saveData[] = "\t\t// {$column['column_comment']}\r\n\t\t\$this->saveData['{$column['column_name']}'] = \$this->params['{$column['column_name']}'];";
            }
            $searchWhere[] = "\t\t// {$column['column_comment']}\r\n\t\tif(isset(\$this->params['{$column['column_name']}']) && \$this->params['{$column['column_name']}']!='')\r\n\t\t{\r\n\t\t\t\$this->where['{$column['column_name']}'] = \$this->params['{$column['column_name']}'];\r\n\t\t}";
        }
        $validateStr1 = implode(",\r\n",$validate1);
        $validateStr2 = implode(",\r\n",$validate2);
        $saveDataStr = implode("\r\n",$saveData);
        $searchWhereStr = implode("\r\n",$searchWhere);
//        var_dump($columns);
        $className = Hump::camel($table).'Model';
        $tables = explode("_",$table);
        $tDir = APP_PATH.'api/open/'.$dir.implode("/",$tables).'/';
        if(!is_dir($tDir))
        {
            @mkdir($tDir,755,true);
        }
        $date = date('Y/m/d',time());
        $time = date('H:i',time());
        $tNamespace = str_replace("/","\\",$dir).implode("\\",$tables);
        $saveTpl = <<<EOF
<?php
/**
 * Save.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: $date
 * Time: $time
 */
namespace app\\api\\open\\$tNamespace;

use app\\api\\open\\member\\Token;
use app\\api\\model\\$className;
use think\\Db;
use think\\Validate;

class Save extends Token
{
    protected \$id = null;
    protected \$saveData = [];
    /**
     * Save constructor.
     * @throws \Exception
     */
    public function __construct(\$param=[])
    {
        parent::__construct(\$param);

        // 验证请求参数
        \$validate = new Validate([
$validateStr1
        ],[
$validateStr2
        ]);
        \$check = \$validate->check(\$this->params);
        if(\$check === false){
            // 验证失败 输出错误信息
            throw new \Exception(\$validate->getError(),1);
        }
        if(!empty(\$this->params['id']))
        {
            \$this->id = \$this->params['id'];
        }
$saveDataStr
    }
    
    /**
     * @param array \$param
     * @return array
     * @throws \Exception
     */
    public function index(\$param=[])
    {
        Db::startTrans();
        try
        {
            // 保存信息
            \$id = $className::getInstance()->save(\$this->id,\$this->saveData);
            if(!\$id)
            {
                throw new \Exception("保存失败",2);
            }
        }
        catch (\Exception \$e)
        {
            // 出现错误进行回滚处理
            Db::rollback();
            // 统一错误抛出
            throw new \Exception("保存失败：".\$e->getMessage(),\$e->getCode());
        }

        Db::commit();
        return ['id'=>empty(\$this->id)?\$id:\$this->id];
    }
}
EOF;
        $getTpl = <<<EOF
<?php
/**
 * Get.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: $date
 * Time: $time
 */
namespace app\\api\\open\\$tNamespace;

use app\\api\\open\\member\\Token;
use app\\api\\model\\$className;
use app\\common\\Singleton;

class Get extends Token
{
    use Singleton;

    public function __construct(\$param = [])
    {
        try{
            parent::__construct(\$param);
        }catch (\Exception \$e) {
            \$this->member_id = null;
            \$this->token_data = [];
        }
    }
    
    /**
     * @param array \$param
     * @return array|false|null|\PDOStatement|string|\\think\Model
     * @throws \Exception
     */
    public function index(\$param=[])
    {
        // 获取详情
        \$info = $className::getInstance()->get(['id'=>\$param['id']]);
        if(empty(\$info['id']))
        {
            throw new \Exception("查询结果为空",1);
        }
        return \$info;
    }
}
EOF;
        $searchTpl = <<<EOF
<?php
/**
 * Search.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: $date
 * Time: $time
 */
namespace app\\api\\open\\$tNamespace;

use app\\api\\open\\member\\Token;
use app\\api\\open\\Base;
use app\\api\\model\\$className;
use app\\common\\Singleton;

class Search extends Token
{
    protected \$where = [];

    public function __construct(\$param = [])
    {
        try{
            parent::__construct(\$param);
        }catch (\Exception \$e) {
            \$this->member_id = null;
            \$this->token_data = [];
        }
$searchWhereStr
    }
    
    /**
     * @param array \$param
     * @return array|false|null|\PDOStatement|string|\\think\Model
     * @throws \Exception
     */
    public function index(\$param=[])
    {
        // 获取列表
        return $className::getInstance()->getList(\$this->where,[
            'field'=> '*'
        ]);
    }
}
EOF;
        $filename = $tDir.'Save.php';
        if(!is_file($filename))
        {
            @file_put_contents($filename,$saveTpl);
        }
        $filename = $tDir.'Get.php';
        if(!is_file($filename))
        {
            @file_put_contents($filename,$getTpl);
        }
        $filename = $tDir.'Search.php';
        if(!is_file($filename))
        {
            @file_put_contents($filename,$searchTpl);
        }
    }
}